import { CUR_USER_INFOS } from "../configs/keys";

/**
 * format-excel-string
 * @param {string} origin origin-string
 */
function setExcelString(origin) {
  const target = [];
  /** 匹配所有英文字母和数字 */
  const rule = /^[\w\d]$/;

  origin
    .toString()
    .split("")
    .forEach((str) => {
      if (rule.test(str)) {
        target.push(str);
      }
    });

  return target.join("");
}

/**
 * formatTreeData
 * @description 扁平数组的树形结构化
 * @param {[]} origin origin-data
 * @param {string} id id-property
 * @param {string} pid pid-property
 * @return {[]} new-array-with-children
 */
function formatTreeData(origin, id = "id", pid = "pid") {
  const pList = origin.filter((item) => !item[pid]),
    cList = origin.filter((item) => item[pid]);

  _formatTree(pList, cList);

  return pList;

  function _formatTree(parent, children) {
    parent.forEach((p) => {
      children.forEach((c, ci) => {
        if (c[pid] === p[id]) {
          const _children = deepClone(children);
          _children.splice(ci, 1);
          _formatTree([c], _children);
          if (p.children) {
            p.children.push(c);
          } else {
            p.children = [c];
          }
        }
      });
    });
  }
}

/**
 * deep-clone es5-deepclone
 * @param {{}|[]} origin origin-data
 * @return {{}|[]} target-data
 */
function deepClone(origin) {
  if (["string", "number", "boolean"].includes(typeof origin)) {
    return origin;
  }

  var target = Array.isArray(origin) ? [] : {};

  for (var k in origin) {
    if (
      origin[k] !== null &&
      Object.prototype.toString.call(origin[k]) === "[object Object]"
    ) {
      target[k] = deepClone(origin[k]);
    } else {
      target[k] = origin[k];
    }
  }

  return target;
}

/**
 * local-storage-set
 * @param {string} key storage-key
 * @param {[] | {} | string} origin origin-item
 * @return {void}
 */
function setLocalStorage(key, origin) {
  if (!key) {
    return;
  }
  const value = JSON.stringify(origin);
  localStorage.setItem(key, value);
}

/**
 * local-storage-get
 * @description 查询本地缓存, 没有或者转码异常返回: []
 * @param {string} key storage-key
 * @return {[] | {} | string} storage-item
 */
function getLocalStorage(key) {
  if (!key) {
    return null;
  }
  const storageItem = JSON.parse(localStorage.getItem(key) || null);
  return storageItem;
}

/**
 * function-compose
 */
function compose() {
  var fnArgs = Array.prototype.slice.call(arguments);

  return function () {
    var cbArgs = Array.prototype.slice.call(arguments);
    var ctx = this;

    return fnArgs.reduceRight((prev, current) => {
      return current.apply(ctx, Array.isArray(prev) ? prev : [prev]);
    }, cbArgs);
  };
}

/**
 * trans-camel-to-upper 驼峰字符串 -> 大写+下划线字符串
 * @param {string} origin 原始字符串
 * @example OperateSuccess -> OPERATE_SUCCESS
 */
function transCamelToUpper(origin) {
  return origin
    .replace(/[A-Z]/, (str) => "_" + str)
    .split("")
    .map((str) => str.replace(/[a-z]/, (str) => str.toUpperCase()))
    .join("");
}

/**
 * trans-upper-to-camel 大写+下划线字符串 -> 驼峰字符串
 * @param {string} origin 原始字符串
 * @example OPERATE_SUCCESS -> OperateSuccess
 */
function transUpperToCamel(origin) {
  const originList = origin.split("_");

  return originList
    .map((str1) =>
      str1
        .split("")
        .map((str2, str2Idx) => (str2Idx > 0 ? str2.toLowerCase() : str2))
        .join("")
    )
    .join("");
}
/**
 * 字符串首字母转大写
 * @param {string} origin
 */
function strFirstToUpper(origin) {
  const originList = origin.split("");

  const targetList = originList.map((str, strIdx) => {
    if (strIdx === 0) {
      return str.toUpperCase();
    }
    return str;
  });

  return targetList.join("");
}
/**
 * 判断用户是否处于登录状态
 */
function checkHasToken() {
  const curUserInfo = getLocalStorage(CUR_USER_INFOS);
  if (curUserInfo?.userInfos?.token) {
    return true;
  }
  return false;
}

export {
  setExcelString,
  formatTreeData,
  deepClone,
  getLocalStorage,
  setLocalStorage,
  compose,
  transCamelToUpper,
  transUpperToCamel,
  strFirstToUpper,
  checkHasToken,
  // todo ...
};
